package com.fysports.web.kit.tree;

import com.fysports.web.model.system.SystemRole;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * 权限树构建
 * Created by konbluesky
 * Date : 15/7/30 上午12:02
 * Project :jdmdata_server
 */
public class SystemRoleTreeBuilder implements ITreeBuilder<SystemRole> {

    @Override public List<TreeNode<SystemRole>> builderTree(List<SystemRole> resources) {
        List<TreeNode<SystemRole>> roots = new ArrayList<TreeNode<SystemRole>>();
        TreeNode<SystemRole> root = new TreeNode<SystemRole>();
        for (SystemRole resource : resources) {
            if (resource.getParentCode()==null || resource.getParentCode() == null) {
                root = new TreeNode<SystemRole>();
                root.setNode(new SystemRole(resource));
                buildTree(root, resources);
                roots.add(root);
            }
        }
        return roots;
    }


    private void buildTree(TreeNode<SystemRole> root, List<SystemRole> resources) {
        TreeNode<SystemRole> node;
        for (Iterator<SystemRole> iterator = resources.iterator(); iterator.hasNext(); ) {
            SystemRole resource = iterator.next();
            if (root.getNode().getCode().equals(resource.getParentCode())) {
                node = new TreeNode<SystemRole>();
                node.setNode(new SystemRole(resource));
                root.addChild(node);
            }
        }
        if (root.getChildCount() > 0) {
            for (TreeNode<SystemRole> branch : root.getChilds()) {
                if (branch.getNode().getParentCode().equals(root.getNode().getCode())) {
                    buildTree(branch, resources);
                }
            }
        }
    }

}
